package com.hubing.cloud.app.web.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.*;

import javax.swing.text.html.HTMLEditorKit;
import java.util.ArrayList;
import java.util.List;

/**
 * 不同富文本内容封装
 */
public class Html2TxtUtil extends HTMLEditorKit.ParserCallback {

    // 对大概率解析出的标签做处理
    public static String convert (String html) {
        if (StringUtils.isBlank(html)) {
            return "";
        }

        // 反转义
        html = StringEscapeUtils.unescapeHtml4(html.trim());

        StringBuilder sb = new StringBuilder();
        Element doc = Jsoup.parseBodyFragment(html).body();
        List<Node> body = doc.childNodes();
        for (Node node: body) {
            // leaf
            if (node instanceof TextNode) {
                sb.append(((TextNode) node).getWholeText());
            } else if (node instanceof DataNode) {
                DataNode dateNode = (DataNode) node;
                sb.append(dateNode.getWholeData());
            } else if (node instanceof DocumentType) {
            } else if (node instanceof Comment) {
            } else if (node instanceof XmlDeclaration) {
            }
            // not leaf
            else if (node instanceof Element) {
                Element element = (Element) node;
                String tagName = element.tagName();
                if ("img".equals(tagName)) {
                } else {
                    for (Node second: node.childNodes()) {
                        if (second instanceof TextNode) {
                            sb.append(((TextNode) second).getWholeText());
                        } else if (node instanceof DataNode) {
                            DataNode dateNode = (DataNode) node;
                            sb.append(dateNode.getWholeData());
                        } else if (node instanceof DocumentType) {
                        } else if (node instanceof Comment) {
                        } else if (node instanceof XmlDeclaration) {
                        } else if (second instanceof Element) {
                            Element secondElement = (Element) second;
                            String secondTagName = secondElement.tagName();
                            if ("img".equals(secondTagName)) {
                            } else {
                                sb.append(convert(second.toString()));
                            }
                        }
                    }
                }
            }
        }
        return sb.toString();
    }


    public static void main(String[] args) {
        String ss5 = "<div style='' >测试了自己是否知道</div>";
        System.out.println(convert(ss5));
    }
}